<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Loader;
use think\Db;
use think\Config;

use app\common\BaseController;
use app\model\UserModel;
use app\model\AppointmentModel;
use app\model\MeetingModel;
use app\model\ArriveModel;
use app\model\VisiterModel;
/**工具**/
use app\common\Tool\ApiErrDesc;
use redis\Redis;


class Appointment extends BaseController
{
    
    private $table_view_member = 'view_commodity_orders';
    protected $redis = null;

    public function _initialize(){
        $this->noNeedLogin = ['session_set'];
        $this->redis = new Redis();
    } 
    public function add_post(){

        $visittime = trim($this->request->param('visittime'));
        $address = trim($this->request->param('address'));
        $deptid = trim($this->request->param('deptid'));
        $reson = trim($this->request->param('reson'));
        $remark = trim($this->request->param('remark'));
        $companyid = trim($this->request->param('companyid'));
        $type = $this->request->param('type');//vis
        $vis_mobile = $this->request->param('vis_phone')?:'';//已知访客电话

        if(empty($visittime) || empty($address) || empty($reson) ){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }

        if($this->user->companyid == 0 && $type!='vis' && $type!='viss'){
            return toJson(['message'=>'发出邀请前请加入公司','code'=>400]);
        }
        //地点图片
        if($deptid){
            $dept_info = $this->find('dept','id = '.$deptid);
            if($dept_info){
                $address_imagelist = $dept_info['address_image'];
            }
        }else{
             $address_imagelist = '';
        }

        // if(!$deptid){
        //     $deptlist =$this->find('view_company_dept','companyid = '.$this->user->companyid.' and is_security = 0');
        //     if(!$deptlist){
        //         $indata = [
        //             'companyid'=>$this->user->companyid,
        //             'name' => $address,
        //             'createtime' => time(),
        //             'is_security' => 0

        //         ];
        //         $res = $this->insertGetId('dept',$indata);
        //         $deptid = $res;
        //     }else{
        //         $deptid = $deptlist['id'];
        //     }

        // }
        /**预约-发出预约 反向邀请**/
        if($type == 'viss'){
            //根绝访问部门  分配受访人  
            //meeting 和 Appointment 做状态 未审核
            //访客默认接受状态   Appointment auditing 审核 代表受访人接受或拒绝  审核不通过代表拒绝(此处拒绝表Appointment 不是meeting)
            $find_Interviewees = $this->find('view_user','companyid = '.$companyid.' and deptid = '.$deptid.' and Interviewees = 1');
            if(!$find_Interviewees){
                $company_info = $this->find('view_company','id = '.$companyid);
                //return toJson(['message'=>'当前预约地点无受访人','code'=>400]);
            }
            $appindata = [
                'address'=> $address,
                'companyid' => $companyid,
                'deptid' => $deptid,
                'visittime' => strtotime($visittime),
                'reson' => $reson,
                'remark' => $remark,
                'uid' => $find_Interviewees['id']?:NULL,
                'createtime' => time(),
                'type' => 2,
                'address_image' => $address_imagelist,
                ];
            $res_appin = $this->insertGetId('appointment',$appindata);

            $meeting_code = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][1]);

            $meetdata = [
                'uid' => $this->uid,
                'createtime' => time(),
            ];
            $res_meetin = $this->insertGetId('meeting',$meetdata);
            $updata_meetin = [
                'appointmentid' => $res_appin,
                'appointment_companyid' => $companyid,
                'appointment_uid' => $find_Interviewees['id']?:NULL,
                'appointment_deptid' => $deptid,
                'status' => 2,
                'confirm_time' => time(),
                'meeting_code' => $meeting_code,
            ];
            $res = $this->update('meeting','id = '.$res_meetin,$updata_meetin);

            $arrivedata = [
                'companyid' => $companyid,
                'arrivetime' => time(),
                'uid' => $this->uid,
                'meetingid' => $res_meetin,
                'createtime' => time(),
            ];
            $res_arrive = $this->insertGetId('arrive',$arrivedata);

            $visiterdata = [
                'uid' => $this->uid,
                'companyid' => $companyid,
                'deptid' => $deptid,
                'createtime' => time(),
                'company' => $find_Interviewees['company_name']?:$company_info['name'],
            ];
            $res_vister = $this->insert('visiter',$meetdata);

            if( $res_appin > 0 ){
                /**推送微信消息**/
                Loader::import('Wechat_OA', EXTEND_PATH);
                $wechatOA = new \Wechat_OA();
                
                /**受访人**/
                $u_Appointment = $this->select('view_user','companyid = '.$companyid.' and deptid = '.$deptid.' and Interviewees = 1');
                $url = 'http://devs.zsicp.com/h5/#/pages/user/visitorauditDetails?visitorinfo=';
                $urldata = $this->find('view_new_app_meeting_info_copy','id = '.$res_appin);
                $url = $url.json_encode($urldata);

                $data = [
                'template_id' => 'NrON2M_fanQcweteHXRpWrWbPuerflXMNGfB13EFD_0',
                'array' => [
                    'first' => "访客".$this->user->name."预约申请",
                    'keyword1' => date('Y-m-d H:i',time($appindata['visittime'])),
                    'keyword2' =>  $this->user->name,
                    'keyword3' =>  $appindata['reson'],
                    'keyword4' => date('Y-m-d H:i',time()),
                    'keyword5' => '请审核预约信息',
                    'remark'   => ''
                    ],
                ];

                if(count($u_Appointment)>0){
                    foreach ($u_Appointment as $key => $value) {
                        # code...
                        $result = $wechatOA->send_WXtpl($value['openid'],$data,$url);
                    }
                    
                }
                //积分
                $res = $this->member_integral($this->user->openid,1,'cut','M');
                return toJson(['message'=>'生成预约成功','appointmentid'=>$res_appin,'code'=>'200']);
            }else{
                return toJson(['message'=>'生成预约出错，请联系客服！','code'=>'400']);
            }



        }   
        /**未接受邀请-反向添加邀请(添加预约)**/
        if($type == 'vis'){
            // $property_relation = $this->find('view_property_relation','incompany_id = '.$companyid);
            // if(!$property_relation){
            //     return toJson(['message'=>'参数错误','code'=>400]);
            // }

            $security_uid = $this->redis->get('Vis_addapp_securityuid'.$this->uid);
            if(!$security_uid){return toJson(['message'=>'已超时请重新填写.','code'=>400]);}
            $security_info = $this->find('view_user','id = '.$security_uid);

            if(!$companyid){return toJson(['message'=>'参数错误companyid.','code'=>400]);}
            //分配受访人
            $appointment_user = $this->find('view_user','companyid = '.$companyid.' and deptid = '.$deptid.' and Interviewees = 1 ');
            if(!$appointment_user){
                $appointment_user = $this->find('view_user','companyid = '.$companyid.' and Interviewees = 1 ');
            }
            if(!$appointment_user){return toJson(['message'=>'参数错误appointment_user.','code'=>400]);}
            
            $appindata = [
                'uid' => $appointment_user['id'],
                'visittime' => strtotime($visittime),
                'companyid' => $companyid,
                'deptid' => $deptid,
                'address' => $address,
                'reson' => $reson,
                'remark' => $remark,
                'createtime' => time(),
                'auditing'=>1,
                'visit_phone'=> $vis_mobile,
                'type' => 2,
                'address_image' => $address_imagelist,
            ];
            $res_appin = $this->insertGetId('appointment',$appindata);

            $meeting_code = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][1]);

            $meetdata = [
                'uid' => $this->uid,
                // 'appointmentid' => $res_appin,
                //'appointment_companyid' => $companyid,
                //'appointment_uid' => $appointment_user['id'],
                //'status' => 2,
                'createtime' => time(),
                //'confirm_time' => time(),
                //'meeting_code' => $meeting_code,
                //'security_uid' => $security_uid,
            ];
            $res_meetin = $this->insertGetId('meeting',$meetdata);
            $updata_meetin = [
                'appointmentid' => $res_appin,
                'appointment_companyid' => $companyid,
                'appointment_uid' => $appointment_user['id'],
                'status' => 2,
                'confirm_time' => time(),
                'meeting_code' => $meeting_code,
                'security_uid' => $security_uid,
            ];
            $res = $this->update('meeting','id = '.$res_meetin,$updata_meetin);

            $arrivedata = [
                'companyid' => $companyid,
                'arrivetime' => time(),
                'uid' => $this->uid,
                'meetingid' => $res_meetin,
                'createtime' => time(),
                //'passtime' => time(),
                'status' => 1, 
            ];
            $res_arrive = $this->insertGetId('arrive',$arrivedata);

            $visiterdata = [
                'uid' => $this->uid,
                'companyid' => $companyid,
                'deptid' => $deptid,
                'createtime' => time(),
                'company' => $appointment_user['company_name'],
            ];
            $res_vister = $this->insert('visiter',$meetdata);

        /**推送微信消息**/
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        
        /**受访人**/
        $u_Appointment = $this->find('view_new_app_meeting_info','appointmentid = '.$res_appin);
        $url = 'http://devs.zsicp.com/h5/#/pages/yuyuejilu/recordDetails?detaildata=';
        $urldata = [
            'id' => $res_appin,
            'showtype' => 2,
            'appinfo' => $u_Appointment
        ];
        $url = $url.json_encode($urldata);

        $openid = $appointment_user['openid']; 
        
        $data = [
        'template_id' => 'NrON2M_fanQcweteHXRpWrWbPuerflXMNGfB13EFD_0',
        'array' => [
            'first' => "访客".$this->user->name."到达公司门口",
            'keyword1' => date('Y-m-d H:i',time($u_Appointment['app_visittime'])),
            'keyword2' =>  $this->user->name,
            'keyword3' =>  $u_Appointment['app_reson'],
            'keyword4' => date('Y-m-d H:i',time()),
            'keyword5' => '访客到达',
            'remark'   => '请做好接待访客准备.'
            ],
        ];
        $result = $wechatOA->send_WXtpl($openid,$data,$url);

        /**保安**/
        $url = 'http://devs.zsicp.com/h5/#/pages/securityguard/useraudit?companyid='.$companyid.'&meetingid='.$res_meetin.'&door=A';
            $openid = $security_info['openid']; 
            $data = [
            'template_id' => 'NrON2M_fanQcweteHXRpWrWbPuerflXMNGfB13EFD_0',
            'array' => [
                'first' => "访客".$this->user->name."到达门口,请检查放行",
                'keyword1' => date('Y-m-d H:i',time($u_Appointment['app_visittime'])),
                'keyword2' =>  $this->user->name,
                'keyword3' =>  $u_Appointment['app_reson'],
                'keyword4' => date('Y-m-d H:i',time()),
                'keyword5' => '公司门口',
                'remark'   => '请及时确认放行.'
                ],
            ];
            $result = $wechatOA->send_WXtpl($openid,$data,$url);
            //积分--
            $res = $this->member_integral($this->user->openid,1,'cut','M');
            return toJson(['message'=>'生成邀请成功','appointmentid'=>$res_appin,'code'=>'200']);
        }
        //end 未预约 反向邀请

        //正常邀请
        $appData = new AppointmentModel;  
        $appData->uid = $this->uid;

        $appData->visittime = strtotime($visittime);
        $appData->companyid = $this->user['companyid'];
        $appData->deptid  = $deptid;
        $appData->address = $address;
        $appData->reson = $reson;
        $appData->remark = $remark;
        $appData->createtime = time();
        $appData->type = 1;
        $appData->address_image = $address_imagelist;
        $appData->save();

        if( $appData->id > 0 ){
            //积分
            $res = $this->member_integral($this->user->openid,1,'cut','C');
            return toJson(['message'=>'生成邀请成功','appointmentid'=>$appData->id,'code'=>'200']);
        }else{
            return toJson(['message'=>'生成邀请出错，请联系客服！','code'=>'400']);
        }      


    }
    /**
     * 修改邀请|预约 
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-19T10:56:58+0800
     * @LastTime     2020-11-19T10:56:58+0800
     * @return       [type]                       [description]
     * @remark 两种角色 都可修改邀请或预约信息 
     */
    public function edit_post(){     
        $id = trim($this->request->param('id'));
        $visittime = trim($this->request->param('visittime'));
        $address = trim($this->request->param('address'));
        $deptid = trim($this->request->param('deptid'));
        $reson = trim($this->request->param('reson'));
        $remark = trim($this->request->param('remark'));
        $url = trim($this->request->param('url'));

        if(empty($url) || empty($id) || empty($visittime) || empty($address) || empty($reson) ){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }
        // 启动事务
        Db::startTrans();
        try{
            $appointmentData = $this->find('view_new_app_meeting_info_copy','id = '.$id);
            $updata = ['deptid'=>$deptid,'visittime'=>strtotime($visittime),'address'=>$address,'reson'=>$reson,'remark'=>$remark,'auditing'=>0];
            //$appointmentData = Db::table('appointment')->where('id', $id)->find();

            Db::table('appointment')->where('id', $id)->update($updata);
            
            //$appointmentData = Db::table('meeting')->where('appointmentid',$id)->where('status','>',1)->column('uid');
            //Db::table('meeting')->where('appointmentid',$id)->where('status','>',1)->update(['status'=>0]);
            Db::commit(); 
            // 提交事务
            

           switch ($appointmentData['type']) {
               case 1:
                   //邀请弹回
                   $userData = Db::table('view_user')->where('id','in',$appointmentData['app_uid'])->column('openid');
                   $check_meeting = $this->find('meeting','appointmentid = '.$id.' and uid = '.$this->uid);
                   $meeting_uid = $this->uid;

                   # code...
                   break;
               case 2:
                   //预约
                   $userData = Db::table('view_user')->where('id','in',$appointmentData['vister_uid'])->column('openid');
                   $check_meeting = $this->find('meeting','appointmentid = '.$id.' and uid = '.$appointmentData['vister_uid']);
                   $meeting_uid = $appointmentData['vister_uid'];
                   # code...
                   # 
                   break;
               default:
                   return toJson(['message'=>'参数错误uid','code'=>400]);
                   # code...
                   break;
           }
           
           //meeting check
           if($check_meeting==NULL){

              $meeting_code = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][1]);
              $in_meetingdata = [
                'uid' => $meeting_uid,
                'appointment_companyid' => $appointmentData['companyid'],
                'appointmentid' => $id,
                'appointment_deptid' => $appointmentData['deptid'],
                'appointment_uid' => $appointmentData['type']==1?$appointmentData['app_uid']:$appointmentData['vister_uid'],
                'createtime' => time(),
                'status' => 0,
                'meeting_code' => $meeting_code,
              ];
              $re_meetingid = $this->insertGetId('meeting',$in_meetingdata);
              // 同时插入arrive
              $in_arrivedata = [
                'companyid'=>$appointmentData['companyid'],
                'meetingid'=>$re_meetingid,
                'status' =>0,
                'uid' => $meeting_uid,//访客id
                'createtime' => time(),
              ];

              $this->insertGetId('arrive',$in_arrivedata);
              

           }else{
                $up_meetingdata = [
                    'uid' => $meeting_uid,
                    'appointment_companyid' => $appointmentData['companyid'],
                    'appointmentid' => $id,
                    'appointment_deptid' => $appointmentData['deptid'],
                    'appointment_uid' => $appointmentData['type']==1?$appointmentData['app_uid']:$appointmentData['vister_uid'],
                    'status' => 0,
              ];
              $this->update('meeting','appointmentid = '.$id.' and uid = '.$meeting_uid,$up_meetingdata);
           }
           
           



            if($userData){
                $url = "http://devs.zsicp.com/h5/?code=061gfXZv3hMZkV2NaS71w3YXpHf2gfXZr&state=123#/pages/yaoqing/xiangqing?sharebtn=YES&detailDate=";
                $url = $url.json_encode($appointmentData);

                //此处信息是推送回给对方
                Loader::import('Wechat_OA', EXTEND_PATH);
                $wechatOA = new \Wechat_OA();
                foreach($userData as $item){
                    $data = ['title'=>'邀请信息更新通知',
                            'openid'=>$item,
                            'name'=>$this->user->name,
                            'mobile'=>$this->user->mobile,
                            'visittime'=>$visittime,
                            'status'=>'等待重新确认',
                            'remark'=>"{$this->user->name}更新了邀请信息，请查看",
                            'url'=>$url
                    ];
                    $result = $wechatOA->send_message($data);
                }
            }

            return toJson(['message'=>'修改成功','code'=>200]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return toJson(['message'=>'数据出错，请联系客服！','code'=>'400']);
        }
    }
                       
    public function delete_post(){
        $id = trim($this->request->param('id'));

        if(empty($id)){
            return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        }

        $appointmentData = AppointmentModel::where('id','eq',$id)->find();
        if(empty($appointmentData)){
            return toJson(['message'=>'邀请信息不存在','code'=>400]);
        }

        $appointmentData->delete();

        return toJson(['message'=>'删除邀请成功','code'=>200]);
    }
    /**
     * 获取邀请详情
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-30T11:29:15+0800
     * @LastTime     2020-11-30T11:29:15+0800
     * @return       [type]                       [description]
     * @param [type] $[name] [<description>]
     *         id 此处id为appointment的id(全部转向appointment表) 不是meeting的id
     */
    public function info_get(){

        $field = 'app.*,u.name as uname,u.mobile as mobile,u.headimgurl as headimgurl,u.personimg as personimg,u.address as address,u.company_name as company_name,u.dept_name as dept_name';
        $id = trim($this->request->param('id'));

        // $appointment_info = $this->find('view_new_app_meeting_info','id = '.$id);
        // if(!$appointment_info){return toJson(['message'=>'邀请信息不存在','code'=>'400']);}
        // $id = $appointment_info['appointmentid'];

        $meeting_code = trim($this->request->param('meeting_code'));

        if($meeting_code){
            $where = 'meeting_code = "'.$meeting_code.'"';
            $meetingData = $this->find('meeting',$where);
            if(!$meetingData){return toJson(['message'=>'邀请信息不存在','code'=>'400']);}
            $appointmentData = AppointmentModel::alias('app')
                                            ->field($field)
                                            ->join('view_user u','app.uid=u.id','left')
                                            ->where('app.id','eq',$meetingData['appointmentid'])
                                            ->find();
            if(empty($appointmentData)){
                return toJson(['message'=>'邀请信息不存在','code'=>'400']);
             }
            $appointmentData->createtime = date('Y-m-d H:i:s',$appointmentData->createtime);
            $appointmentData->visittime = date('Y-m-d H:i:s',$appointmentData->visittime);
            $appointmentData->meeting_code = $meeting_code;
            if($id){
                $appointment_info = $this->find('view_new_app_meeting_info_copy','id = '.$id);
                $appointmentData['appointment_details'] = $appointment_info;
            }
            return toJson(['data'=>$appointmentData,'code'=>'200']);
        }
        /**end**/
        if(empty($id)){
            return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        }



        $appointmentData = AppointmentModel::alias('app')
                                            ->field($field)
                                            ->join('view_user u','app.uid=u.id','left')
                                            ->where('app.id','eq',$id)
                                            ->find();
        if(empty($appointmentData)){
            return toJson(['message'=>'邀请信息不存在','code'=>'400']);
        }
        $where1 = 'appointmentid = '.$id.' and vister_uid = '.$this->uid;
        $where2 = 'appointmentid = '.$id.' and app_uid = '.$this->uid;
        $res1 = $this->find('view_new_app_meeting_info',$where1);
        $res2 = $this->find('view_new_app_meeting_info',$where2);
        /**example vister**/
        if($res1){
            $meeting_code = $res1['meeting_code'];
            $appointmentData['meeting_code'] = $meeting_code;
            $appointmentData['meetinginfo'] = $res1;

        }
        if($res2){
            $meeting_code = $res2['meeting_code'];
            $appointmentData['meeting_code'] = $meeting_code;
            $appointmentData['meetinginfo'] = $res2;

        }
        if(!$res1 && !$res2){
             $meeting_code = NULL;
            $appointmentData['meeting_code'] = NULL;
            $appointmentData['meetinginfo'] = NULL;
        }
        $appointmentData->createtime = date('Y-m-d H:i',$appointmentData->createtime);
        $appointmentData->visittime = date('Y-m-d H:i',$appointmentData->visittime);


        // $checkis_accept = '';

        // $meetingData = MeetingModel::where('appointmentid','eq',$id)->where('uid','eq',$this->uid)->find();
        // if(!empty($meetingData)){
        //     $meeting_status = $meetingData->status==1
        // }

        // if($this->uid != $appointmentData->uid){
        //     $meetingData = MeetingModel::where('appointmentid','eq',$id)->where('uid','eq',$this->uid)->find();
        //     if(!empty($meetingData)){
        //         $appointmentData->status = $meetingData->status;
        //     }else{
        //         $appointmentData->status = 0;
        //     }
        // }
        $appointment_info = $this->find('view_new_app_meeting_info_copy','id = '.$id);


        $appointmentData['appointment_details'] = $appointment_info?$appointment_info:['arrive_status'=>0,'meeting_status'=>0,'appointment_status'=>$appointmentData->status];

        return toJson(['data'=>$appointmentData,'code'=>'200']);
    }


    public function getlist_get(){
        $page = trim($this->request->param('page'));
        if($page==1){$page=0;}
        $pagesize = trim($this->request->param('pagesize'));
        $keyword = trim($this->request->param('keyword'));
        $type  = $this->request->param('type');  //viss


        $page = empty($page) ? 0 : $page;
        $pagesize = empty($pagesize) ? 10 : $pagesize;
        //预约申请 审核列表
        //$this->user->roleid= 1;
        if($type == 'viss'){
            $roleid = $this->user->roleid;
            switch ($roleid) {
                case 1:
                    $where = 'auditing = 0 and type = 2';
                    # code...
                    break;
                case 2:
                case 8:
                    $where = 'companyid = '.$this->user->companyid.' and auditing = 0 and type = 2';
                    break;
                case 5:
                case 6:

                    $where = 'companyid = '.$this->user->companyid.' and auditing = 0 and (type = 2 and app_uid = '.$this->uid.') or ( type = 1 and vister_uid = '.$this->uid.') ';

                    $where = 'companyid = '.$this->user->companyid.' and type = 1 and status = 0 and  auditing = 0 and app_uid = '.$this->uid;
                    $where = 'companyid = '.$this->user->companyid.' and type = 2 and status = 0 and  auditing = 0 and vister_uid = '.$this->uid;
                    //return toJson(['message'=>'获取预约审核列表成功','code'=>'200','data'=>[],'total'=>0]);
                    break;
                case 3:
                    $where = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and auditing = 0 and type = 2';
                    break;
                case 4:
                    $where = 'companyid = '.$this->user->companyid.' and deptid = '.$this->user->deptid.' and auditing = 0 and type = 2 and app_uid = '.$this->uid;
                    break;
                default:
                    //$where = 'auditing = 0 and type = 2 and vister_uid = '.$this->uid;
                    return toJson(['message'=>'无权限请求','code'=>'400','data'=>[]]);
                    # code...
                    break;
            }
            //$where = 'auditing = 0';
            $res = $this->selectView('view_new_app_meeting_info_copy', $where, '*', $page, $pagesize, 'app_visittime desc');
            $total = $this->totalView('view_new_app_meeting_info_copy',$where);
            return toJson(['message'=>'获取预约审核列表成功','code'=>'200','data'=>$res,'total'=>$total]);
        }
        
        $where = $keyword ? ":name like %".$keyword."%" : '1=1';


        $fields = 'a.id,a.uid,u1.name as uname,u1.mobile as mobile,u1.headimgurl as headimgurl,u1.companyid as cid,c1.name as cname,u1.deptid as deptid,d1.name as dname, a.visittime,a.address,a.reson,a.remark,a.createtime,
        m.uid as uid2,u2.name as uname2,u2.mobile as mobile2,u2.headimgurl as headimgurl2,u2.companyid as cid2,c2.name as cname2,u2.deptid as deptid2,d2.name as dname2,
        m.id as mid,m.createtime as uptime,m.`confirm_time`,m.status,m.reson as refusereson';

        if( $this->user->roleid == Config::get('ROLE_SYSTEM_MANAGER') ){
            $appointmentList = MeetingModel::alias('m')
                                            ->field($fields)
                                            ->join('appointment a','m.appointmentid=a.id','left')
                                            ->join('user u1','a.uid =u1.id','left')
                                            ->join('company c1','u1.companyid =c1.id','left')
                                            ->join('dept d1','u1.deptid =d1.id','left')
                                            ->join('user u2','m.uid =u2.id','left')
                                            ->join('company c2','u2.companyid =c2.id','left')
                                            ->join('dept d2','u2.deptid =d2.id','left')
                                            ->where($where)
                                            ->where('a.deleteTime is null')
                                            ->page($page,$pagesize)
                                            ->select();
            $total = MeetingModel::where($where)->count();
        }elseif($this->user->roleid == Config::get('ROLE_COMPANY_MANAGER')){
            $appointmentList = MeetingModel::alias('m')
                                            ->field($fields)
                                            ->join('appointment a','m.appointmentid=a.id','left')
                                            ->join('user u1','a.uid =u1.id','left')
                                            ->join('company c1','u1.companyid =c1.id','left')
                                            ->join('dept d1','u1.deptid =d1.id','left')
                                            ->join('user u2','m.uid =u2.id','left')
                                            ->join('company c2','u2.companyid =c2.id','left')
                                            ->join('dept d2','u2.deptid =d2.id','left')
                                            ->where('c1.id','eq',$this->user->companyid)
                                            ->where('a.deleteTime is null')
                                            ->page($page,$pagesize)
                                            ->select();
            $total = MeetingModel::alias('m')
                                    ->join('appointment a','m.appointmentid=a.id','left')
                                    ->join('user u','a.uid =u.id','left')
                                    ->join('company c','u.companyid =c.id','left')
                                    ->where($where)->where('u.companyid','eq',$this->user->companyid)
                                    ->count();
        }else{
            $appointmentList = MeetingModel::alias('m')
                                            ->field($fields)
                                            ->join('appointment a','m.appointmentid=a.id','left')
                                            ->join('user u1','a.uid =u1.id','left')
                                            ->join('company c1','u1.companyid =c1.id','left')
                                            ->join('dept d1','u1.deptid =d1.id','left')
                                            ->join('user u2','m.uid =u2.id','left')
                                            ->join('company c2','u2.companyid =c2.id','left')
                                            ->join('dept d2','u2.deptid =d2.id','left')
                                            ->where('m.uid','eq',$this->uid)
                                            ->where('a.deleteTime is null')
                                            ->page($page,$pagesize)
                                            ->select();
            $total = MeetingModel::where($where)->where('uid','eq',$this->uid)->count();
        }

        if($appointmentList){
            foreach($appointmentList as &$item){
                $item->visittime = !empty($item->visittime) ? date('Y-m-d H:i:s',$item->visittime) : 0;
                $item->uptime = !empty($item->uptime) ? date('Y-m-d H:i:s',$item->uptime) : 0;
                $item->confirm_time = !empty($item->confirm_time) ? date('Y-m-d H:i:s',$item->confirm_time) : 0;                 
            }
        }
        $totalpage = $total > 0 ? ceil($total/$pagesize) : 0;

        return toJson(['message'=>'获取邀请列表成功','code'=>'200','data'=>$appointmentList,'total'=>$total,'totalpage'=>$totalpage]);
    }

    // public function getlist_get(){
    //     $page = trim($this->request->param('page'));
    //     $pagesize = trim($this->request->param('pagesize'));
    //     $keyword = trim($this->request->param('keyword'));

    //     $page = empty($page) ? 1 : $page;
    //     $pagesize = empty($pagesize) ? 10 : $pagesize;
        
    //     $where = $keyword ? ":name like %".$keyword."%" : '1=1';


        // if( $this->user->roleid == Config::get('ROLE_SYSTEM_MANAGER') ){
        //     $appointmentList = AppointmentModel::where($where)->page($page,$pagesize)->select();
        //     $total = AppointmentModel::where($where)->count();
        // }elseif($this->user->roleid == Config::get('ROLE_COMPANY_MANAGER')){
        //     $appointmentList = AppointmentModel::where($where)->where('companyid','eq',$this->user->companyid)->page($page,$pagesize)->select();
        //     $total = AppointmentModel::where($where)->where('companyid','eq',$this->user->companyid)->count();
        // }else{
        //     $appointmentList = AppointmentModel::where($where)->where('uid','eq',$this->uid)->page($page,$pagesize)->select();
        //     $total = AppointmentModel::where($where)->where('uid','eq',$this->uid)->count();
        // }

        // $totalpage = $total > 0 ? ceil($total/$pagesize) : 0;

        // return ['message'=>'获取邀请列表成功','code'=>'200','data'=>$appointmentList,'total'=>$total,'totalpage'=>$totalpage];
    // }
    /**
     * 接受邀请
     * @HtttpRequest        |post
     * @Author       
     * @param [type] $[name] [<description>]
     *                 id       邀请id
     *                 url      模板url
     *                 app_uid  邀请人id
     *                 auditing 审核状态修改
     *                 type     viss-反向邀请 预约
     * 
     * @DateTime            
     * @LastTime     2020-07-30T10:48:21+0800
     * @return       [type]                   [description]
     */
    public function accept_post(){
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        $id = trim($this->request->param('id'));
        $url = trim($this->request->param('url'));
        $app_uid = trim($this->request->param('app_uid'));
        $auditing = trim($this->request->param('auditing'));/*审核*/
        $type = trim($this->request->param('type')); //viss
        if(empty($id)){
            return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        }
        //预约审核
        if($type == 'viss'){
            $appointment_info =  $this->find('view_new_app_meeting_info_copy','id = '.$id);
            if(!$appointment_info){return toJson(['message'=>'邀请信息不存在','code'=>'400']);}
            if($appointment_info['vister_uid']== $this->uid){return toJson(['message'=>'该预约属于自己,无需确认','code'=>'400']);}

            $res_auditing = $this->find('appointment','id = '.$id);
            if($res_auditing['auditing']!=0){return toJson(['message'=>'请勿重复操作','code'=>'400']);}
            $this->update('appointment', 'id = '.$id,['auditing'=>1,'uid'=>$this->uid]);
            $this->update('meeting', 'appointmentid = '.$id,[
                'appointment_companyid'=>$this->user->companyid?:NULL,
                'appointment_deptid'=>$this->user->deptid?:NULL,
                'appointment_uid'=> $this->uid?:NULL,
                'status'=> 2,
            ]);
            $url = 'http://devs.zsicp.com/h5/#/pages/myyuyue/myyuyue';
            // $url = 'http://devs.zsicp.com/h5/#/pages/user/visitorauditDetails?visitorinfo=';
            // $urldata = $this->find('view_new_app_meeting_info_copy','id = '.$res_appin);
            // $url = $url.json_encode($urldata);

            $data = [
            'template_id' => 'EeNfEuNHaQrLn2S9Rvf5tbKuh2HRez5GCJUOj0tD__w',
            'array' => [
                'first' => "预约申请审核通知",
                'keyword1' => $appointment_info['vister_name'],
                'keyword2' =>  $appointment_info['vister_mobile'],
                'keyword3' =>  $appointment_info['app_visittime'],
                'keyword4' => "受访人接受了您的预约",
                'remark'   => ''
                ],
            ];
            $find_openid = $this->find('view_user','id = '.$appointment_info['vister_uid']);
            $result = $wechatOA->send_WXtpl($find_openid['openid'],$data,$url);
            return toJson(['message'=>'审核通过','code'=>'200']);
        }
        //邀请正常审核
        if($auditing == '2' || $auditing == '1'){
            $where= 'id = '.$id;
            switch ($auditing) {
                case 2:
                    # code...
                    $data = ['auditing'=>0];
                    $auditingres = $this->update('appointment',$where,$data);
                    return toJson(['message'=>'审核不通过','code'=>'200']);
                    break;
                case 1:
                    # code...
                    $data = ['auditing'=>1];
                    $auditingres = $this->update('appointment',$where,$data);
                    return toJson(['message'=>'审核通过','code'=>'200']);
                    break;
                default:
                    # code...
                    break;
            }

        }
        //正常接受邀请
        $appointmentData = AppointmentModel::alias('app')
                                            ->field('app.*,user.openid,user.name as uname,user.mobile')
                                            ->join('user','app.uid=user.id','left')
                                            ->where('app.id','eq',$id)
                                            ->find();
        if(empty($appointmentData)){
            return toJson(['message'=>'邀请信息不存在','code'=>'400']);
        }
        if($appointmentData->uid == $this->uid){
            return toJson(['message'=>'该邀请属于自己,无需确认','code'=>'400']);
        }
        $meetingData = MeetingModel::where('appointmentid','eq',$id)->where('uid','eq',$this->uid)->find();
        if(!empty($meetingData)){
            return toJson(['message'=>'邀请信息已确认','code'=>'400']);
        }
        $res = $this->checkupphone($id);
        $where = 'uid ='.$this->uid.' and companyid = '.$appointmentData->companyid;
        $order = 'createtime desc';
        $check_Question = Db::table('answer')->where($where)->order($order)->find();
       //1-已答，0-未答
        // if($check_Question){ 
           $is_question =  $check_Question['answered']==1? 1:0;
          // }
        $check_meeting = $this->find('meeting','appointmentid = '.$id);
        if($check_meeting==NULL){
            $meetingData = new MeetingModel;
            $meetingData->uid = $this->uid;
            
            if($this->user->companyid != NULL){
                $meetingData->companyid = $this->user->companyid;
            }
            $meeting_code = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][1]);
            $meetingData->appointmentid = $id;
            $meetingData->appointment_companyid = $appointmentData->companyid;
            $meetingData->appointment_uid = $appointmentData->uid;
            $meetingData->status = 2;
            $meetingData->createtime = time();
            $meetingData->confirm_time = time();
            $meetingData->meeting_code = $meeting_code;
            $meetingData->save();
        }


        $arriveData = new ArriveModel;
        $arriveData->uid = $this->uid;
        $arriveData->meetingid = $meetingData->id;
        $arriveData->createtime = time();
        $arriveData->save();

        $visterData = new VisiterModel;
        $visterData->uid = $this->uid;
        $visterData->companyid = $appointmentData->companyid;
        $visterData->deptid = $appointmentData->deptid;
        $visterData->createtime = time();
        $visterData->save();

        
        $urldata = json_encode($appointmentData);
        $url = 'http://devs.zsicp.com/h5/#/pages/yaoqing/xiangqing?detailDate='.$urldata;
        

        $appointment_info = $this->find('view_appointment','id = '.$id);

        /**受访人**/
        $openid = $appointmentData->openid; 

        $data = [
        'template_id' => 'telsykZ-M7qFuH1K25-MsSTQ84otEgoW-toRqn6_Its',
        'array' => [
            'first' => "您好,{$this->user->name}接受了您的邀请！",
            'keyword1' => $appointment_info['company_name'],
            'keyword2' => $this->user->name,
            'keyword3' => $this->user->mobile,
            'keyword4' => date('Y-m-d H:i',$appointment_info['visittime']),
            'keyword5' => $appointment_info['reson'],
            'remark'   => '请您根据预约做好相关准备。'
            ],
        ];
        $result = $wechatOA->send_WXtpl($openid,$data,$url);
        /**访客**/
        $url = 'http://devs.zsicp.com/h5/#/pages/yaoqing/InviteQrCode?id='.$appointmentData->id;

        $url = $url.'&meeting_code='.$meeting_code;

        $data = ['title'=>'邀请接受通知',
                'openid'=>$this->user->openid,
                'name'=>$appointmentData->uname,
                'mobile'=>$appointmentData->mobile,
                'visittime'=>date('Y-m-d H:i',$appointmentData->visittime),
                'status'=>'接受邀请',
                'remark'=>"您接受了{$appointmentData->uname}的邀请",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);

        $redata = [
            'is_question' => $is_question
        ];
        return toJson(['message'=>'接受邀请成功','code'=>'200','data'=>$redata]);
    }

    public function confirm_post(){
        $id = trim($this->request->param('id'));
        $url = trim($this->request->param('url'));

        if(empty($id)){
            return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        }

        $meetingData = MeetingModel::where('appointmentid','eq',$id)->find();
        if(empty($meetingData)){
            return toJson(['message'=>'确认信息不存在','code'=>'400']);            
        }

        $appointmentData = AppointmentModel::alias('app')
                                            ->field('app.*,user.openid,user.name as uname,user.mobile')
                                            ->join('user','app.uid=user.id','left')
                                            ->where('app.id','eq',$id)
                                            ->where('app.uid','eq',$this->uid)
                                            ->find();
        if(empty($appointmentData)){
            return toJson(['message'=>'邀请信息不存在','code'=>'400']);
        }

        $meetingData->status = 2;
        $meetingData->confirm_time = time();
        $meetingData->save();

        
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        $data = ['title'=>'邀请确认通知',
                'openid'=>$appointmentData->openid,
                'name'=>$this->user->name,
                'mobile'=>$this->user->mobile,
                'visittime'=>date('Y-m-d H:i',$appointmentData->visittime),
                'status'=>'审核成功',
                'url'=>$url,
                'remark'=>"您通过了{$appointmentData->uname}的审核",
        ];
        $wechatOA->send_message($data);

        $data = ['title'=>'邀请确认通知',
                'openid'=>$this->user->openid,
                'name'=>$appointmentData->uname,
                'mobile'=>$appointmentData->mobile,
                'visittime'=>date('Y-m-d H:i',$appointmentData->visittime),
                'status'=>'审核成功',
                'url'=>$url,
                'remark'=>"您已确认{$appointmentData->uname}的邀请",
        ];
        $wechatOA->send_message($data);


        return toJson(['message'=>'确认邀请成功','code'=>'200']);
    }
    /**
     * 拒绝邀请|审核不通过
     * @Author      GNLEON
     * @HttpRequest                                              get|post
     * @Param             
     * type viss 反向邀请 (预约申请审核)                        -
     * @DateTime    2020-11-13
     * @LastTime                                  2020-11-13
     * @copyright   [copyright]
     * @license     [license]
     * @return      [type]                        [description]
     */
    public function refuse_post(){
        Loader::import('Wechat_OA', EXTEND_PATH);
        $id = trim($this->request->param('id'));
        $refusereson = trim($this->request->param('refusereson'));
        $url = trim($this->request->param('url'));
        $type = trim($this->request->param('type')); //viss
        $auditing = trim($this->request->param('auditing'));

        if(empty($id)){
            return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        }
        if(empty($refusereson)){
            return toJson(['message'=>'拒绝理由不能为空','code'=>400]);
        }
        //拒绝审核通过
        if($type == 'viss'){
            $appointment_info =  $this->find('view_new_app_meeting_info_copy','id = '.$id);
            if(!$appointment_info){return toJson(['message'=>'邀请信息不存在','code'=>'400']);}
            if($appointment_info['vister_uid']== $this->uid){return toJson(['message'=>'该预约属于自己,无需确认','code'=>'400']);}
            //审核不通过 结束预约流程
             $res_auditing = $this->find('appointment','id = '.$id);
            if($res_auditing['auditing']!=0){return toJson(['message'=>'请勿重复操作','code'=>'400']);}
            $this->update('appointment', 'id = '.$id,['auditing'=>2,'uid'=>$this->uid,'status'=>1]);
            $meeting_up_data = ['status'=>2,'uid'=>$this->uid];
            if($refusereson){
                $meeting_up_data['reson'] = $refusereson;
            }
            $this->update('meeting', 'appointmentid = '.$id.' and uid = '.$this->uid,$meeting_up_data);
            
            //发送拒绝微信消息
            $appointmentData = $this->find('view_new_app_meeting_info_copy','id = '.$id);
            $vister_userinfo =  $this->find('view_user','id =  '.$appointmentData['vister_uid']);
           
            $wechatOA = new \Wechat_OA();
            $data = ['title'=>'预约拒绝通知',
                    'openid'=>$vister_userinfo['openid'],
                    'name'=>$appointmentData['vister_name'],
                    'mobile'=>$appointmentData['vister_mobile'],
                    'visittime'=>date('Y-m-d H:i',$appointmentData['app_visittime']),
                    'status'=>'拒绝预约',
                    'remark'=>$appointmentData['app_reson'],
                    'url'=>$url
            ];
            $wechatOA->send_message($data);
    
            $data = ['title'=>'预约拒绝通知',
                    'openid'=>$this->user->openid,
                    'name'=>$appointmentData['vister_name'],
                    'mobile'=>$appointmentData['vister_mobile'],
                    'visittime'=>date('Y-m-d H:i',$appointmentData['app_visittime']),
                    'status'=>'拒绝预约',
                    'remark'=>"您拒绝了{$vister_userinfo['name']}的预约",
                    'url'=>$url
            ];
            $wechatOA->send_message($data);

            return toJson(['message'=>'审核不通过','code'=>'200']);
        }
        //end
        $appointmentData = AppointmentModel::alias('app')
                                            ->field('app.*,user.openid,user.name as uname,user.mobile')
                                            ->join('user','app.uid=user.id','left')
                                            ->where('app.id','eq',$id)
                                            ->find();
        if(empty($appointmentData)){
            return toJson(['message'=>'邀请信息不存在','code'=>'400']);
        }
        if($appointmentData->uid == $this->uid){
            return toJson(['message'=>'该邀请属于自己,无需确认','code'=>'400']);
        }
        $meetingData = MeetingModel::where('appointmentid','eq',$id)->where('uid','eq',$this->uid)->find();
        if(!empty($meetingData)){
            return toJson(['message'=>'邀请信息已确认','code'=>'400']);
        }
        $res = $this->checkupphone($id);
        $meetingData = new MeetingModel;
        $meetingData->uid = $this->uid;
        $meetingData->companyid = $this->user->companyid;
        $meetingData->appointmentid = $id;
        $meetingData->appointment_companyid = $appointmentData->companyid;
        $meetingData->reson = $refusereson;
        $meetingData->status = 1;
        $meetingData->createtime = time();
        $meetingData->save();

        

        $wechatOA = new \Wechat_OA();
        $data = ['title'=>'邀请拒绝通知',
                'openid'=>$appointmentData->openid,
                'name'=>$this->user->name,
                'mobile'=>$this->user->mobile,
                'visittime'=>date('Y-m-d H:i',$appointmentData->visittime),
                'status'=>'拒绝邀请',
                'remark'=>$appointmentData->reson,
                'url'=>$url
        ];
        $wechatOA->send_message($data);

        $data = ['title'=>'邀请拒绝通知',
                'openid'=>$this->user->openid,
                'name'=>$appointmentData->uname,
                'mobile'=>$appointmentData->mobile,
                'visittime'=>date('Y-m-d H:i',$appointmentData->visittime),
                'status'=>'拒绝邀请',
                'remark'=>"您已拒绝了{$appointmentData->uname}的邀请",
                'url'=>$url
        ];
        $wechatOA->send_message($data);

        return toJson(['message'=>'拒绝邀请成功','code'=>'200']);
    }

    /**
     * 设为指定受访人
     * @HtttpRequest                          get|post
     * @Author       GNLEON
     * @param [type] $[name] [<description>]
     *                  uid  访客id
     * @DateTime     2020-08-20T14:46:23+0800
     * @LastTime     2020-08-20T14:46:23+0800
     * @return       [type]                   [description]
     * @remark       差个判断是否企业经营者 是否某个套餐 防止调用该API(目前前端限制)
     */
    public function choiceAppuser(){
        $uid = $this->request->param('uid');
        if(empty($uid)){return toJson(['message'=>'参数不全，请检查','code'=>'400']);}
        // if($uid==$this->uid){return toJson(['message'=>'FAILD','code'=>'400']);}
        /**/
        $search[0] = 'userid = '.$this->uid;
        // $search[0] = 'userid = 147';
        $search[1] = 'status = 2 and payTime is not null and deletetime is null';
        $search[2] = 'commodity_year = 0 and commodity_month = 1 and commodity_day = 0';
        $search[3] = 'expritime > '.time();
        $where = '';

        foreach ($search as $key => $value) {
            # code...
            if($value){
                $where=$where.$value.' and ';
            }
        }
        $where=substr($where,0,strlen($where)-5);
        $order = 'payTime desc';
        $memberinfo = Db::table($this->table_view_member)->where($where)->order($order)->find();
        if($memberinfo==NULL){$memberinfo['commodity_outAppnumber'] =1;}
        $where = 'companyid = '.$this->user['companyid'].' and Interviewees = 1';
        $sumapp = Db::table('view_user')->where($where)->count();   
        $needchoice = $memberinfo['commodity_outAppnumber']-$sumapp;

        $reinfo['needchoice'] = $needchoice>0?$needchoice:0;

        /*set1*/
        $where ='id = '.$uid;
        $checku = $this->find('user',$where);
        if($checku==NULL){return toJson(['message'=>'用户不存在','code'=>'400']);}
            if($checku['Interviewees'] ==1){
                $data = [
                'Interviewees' => 0
                ];
               
                $res = $this->update('user', $where, $data);
                $reinfo['needchoice'] = $reinfo['needchoice']+1;

                //last app user
                    
                    if($reinfo['needchoice'] == 1){
                        $boos_info = $this->find('view_user','companyid = '.$this->user['companyid'].' and roleid = 2');
                        if($boos_info && $uid!=$boos_info['id']){
                            $this->update('user','id = '.$boos_info['id'],['Interviewees'=>1]);
                        }
                        $reinfo['needchoice']--;
                    }
                   
                //
                
                return toJson(['message'=>'取消受访人成功','code'=>'200','data'=>$reinfo]);

            } 

        if($needchoice == 0){
            return toJson(['message'=>'设定受访人已上限','code'=>'400','data'=>$reinfo]); 
        }

        /*set2*/

        if($needchoice>0){
            $where = 'id ='.$uid;
            $data = [
                'Interviewees' => 1
            ];  

            $res = $this->update('user', $where, $data);
            $reinfo['needchoice'] = $reinfo['needchoice']!=0?$reinfo['needchoice']-1:0;
            return toJson(['message'=>'设为受访人成功','code'=>'200','data'=>$reinfo]);
        }

        return toJson(['message'=>'设定受访人失败','code'=>'400','data'=>$reinfo]);
        // $checkappnum = Db::table('')->
    
    }
    /**
     * [checkupphone 根绝appointment检查更新是否未注册用户 手机号] ///废弃
     * @HtttpRequest                              get|post
     * @Author       GNLEON
     * @Param
     * @DateTime     2020-11-09T11:10:39+0800
     * @LastTime     2020-11-09T11:10:39+0800
     * @return       [type]                       [description]
     */
    protected function checkupphone($appointment_id){
        $uid = $this->uid;
        $appointment_info = $this->find('appointment','id = '.$appointment_id);
        if(!$this->user->mobile && $appointment_info['visit_phone']){
            $data = [
                'mobile' => $appointment_info['visit_phone'],
            ];
            $res = $this->update('user', 'id = '.$uid, $data);

        }
        return true;
    }

}
